package io.vector.study.springboot.api;

import com.baomidou.mybatisplus.plugins.Page;
import io.vector.study.springboot.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by vector on 2017/5/10.
 */
@RestController
public abstract class BaseApi {

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    public <T> Page<T> extractPageFromRequest() {
        String pageParam = request.getParameter(Constants.PARAM_PAGE);
        String pageSizeParam = request.getParameter(Constants.PARAM_PAGE_SIZE);

        int page = Constants.DEFAULT_PAGE;
        int pageSize = Constants.DEFAULT_PAGE_SIZE;

        try {
            if (StringUtils.isNoneBlank(pageParam)) {
                page = Integer.parseInt(pageParam);
            }
            if (StringUtils.isNotBlank(pageSizeParam)) {
                pageSize = Integer.parseInt(pageSizeParam);
            }
        } catch (NumberFormatException e) {
            throw new ApiException(400, "分页参数错误");
        }

        return new Page<>(page, pageSize);
    }

}
